//
//  FPRepayController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/8.
//

#import "FPRepayController.h"
#import "MQVerCodeInputView.h"
#import "FPAuthenticationFooterView.h"
#import "FPBankCardInfoMainView.h"
#import "FPBankCardModel.h"
#import "FPAddNewBankCardController.h"
#import "FPRepayBankCardCell.h"
#import "FPRepayResultController.h"

@interface FPRepayController () <UITableViewDelegate , UITableViewDataSource>

@property (nonatomic ,strong) MQVerCodeInputView *verView;
@property(nonatomic , strong) UIView *whiteView;
@property(nonatomic , strong) UIView *codeWindow;
@property(nonatomic , strong) UILabel *tip;
//@property(nonatomic , strong) UIImageView *codeImageView;
@property (nonatomic , strong) FPAuthenticationFooterView *footerView;

@property(nonatomic , strong) NSString *code; // !<

@property (weak, nonatomic) IBOutlet UILabel *tipLab;
@property (weak, nonatomic) IBOutlet UILabel *amountLab;
@property (weak, nonatomic) IBOutlet UIView *backView;

@property (nonatomic , strong) FPBankCardInfoMainView *bankCardInfoMainView;
@property (nonatomic , strong) NSMutableArray *bankCardSource;
@property (nonatomic , assign) NSInteger bankCardSelectIndex;
@property (weak, nonatomic) IBOutlet UILabel *tipLab1;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UILabel *selectOtherLab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewHeight;

@end

@implementation FPRepayController

LazyLoadDataSource(bankCardSource);

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)initUI {
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    [self setTitle:@"还款" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.bankCardSelectIndex = -1;
    
    self.backView.backgroundColor = UIColor.whiteColor;
    self.backView.clipsToBounds = YES;
    self.backView.layer.cornerRadius = 8.f;
    self.tipLab.textColor = [UIColor hexColor:@"#3A3A3A"];
    self.tipLab1.textColor = [UIColor hexColor:@"#9A9A9A"];
    self.selectOtherLab.textColor = [UIColor hexColor:@"#6A6A6A"];
    self.lineView.backgroundColor = [[UIColor hexColor:@"#F3F3F3"] colorWithAlphaComponent:.5f];
    
    self.amountLab.text = self.amountString;// [NSString stringWithFormat:@"%.f2", self.amountString.floatValue];
//    self.tipLab2.text = self.termString;
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAuthenticationFooterView.class) owner:nil options:nil].lastObject;
    [self.view addSubview:self.footerView];
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom - 71.f, SCREEN_WIDTH, 71.f);
    self.footerView.selectImgView.hidden = YES;
    self.footerView.privacyLab.hidden = YES;
    [self.footerView.nextBtn setTitle:@"确认支付" forState:(UIControlStateNormal)];
    self.footerView.topHeight.constant = -17.67f; //
//    [self.footerView setShadow];
    self.footerView.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom, SCREEN_WIDTH, UIDevice.safeDistanceBottom)];
    [self.view addSubview:bottomV];
    bottomV.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    
    
    [self.backView addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0.f, 41.f, SCREEN_WIDTH - 32.f, 56.f * 3);
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 56.f;
    self.tableView.contentSize = CGSizeMake(0.f, 0.f);
    self.tableView.alwaysBounceVertical = NO;
    
#pragma mark - 确认付款
    [self.footerView.nextBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
    
        [self initVerView];
    }];
    
    // 查银行卡列表
    [self getBankCardList:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.bankCardSource.count == 0) {
        
        return 1;
    }
    else if (self.bankCardSource.count > 3) {
        
        return 3;
    }
    else {
        
        return self.bankCardSource.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPRepayBankCardCell *cell;
    
    if (!cell) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPRepayBankCardCell.class) owner:nil options:nil].lastObject;
    }
    
    if (self.bankCardSource.count == 0) {
        
        cell.iconImgView.image = IMG(@"icon_bank_info_add_card");
        cell.titleLab.text = @"添加银行卡";
    }
    else {
        
        // icon_bank_card_default -> 如果model 没有银行卡icon
        cell.iconImgView.image = IMG(@"icon_bank_card_default");
        
        FPBankCardModel *model = self.bankCardSource[indexPath.row];
        cell.titleLab.text = [NSString stringWithFormat:@"%@(%@)", model.bankName , [model.bankCard substringFromIndex:(model.bankCard.length - 4)]];
        [cell.iconImgView sd_setImageWithURL:[NSURL URLWithString:[FPUserModel.globalHeadURL stringByAppendingString:model.imagePath]] placeholderImage:IMG(@"icon_bank_card_default")];
        
        if (model.isSelect) {
            
            cell.selectImgView.hidden = NO;
        }
        else {
            
            cell.selectImgView.hidden = YES;
        }
        
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.bankCardSource.count == 0) {
     
        [self selectBankCardAction];
    }
    else {
        
        FPBankCardModel *model = self.bankCardSource[indexPath.row];
        
        for (FPBankCardModel *m in self.bankCardSource) {
            
            m.isSelect = NO;
        }
        
        model.isSelect = YES;
        
        [self.tableView reloadData];
    }
}



#pragma mark - 先查一下银行卡列表 selectLastCard: 最近添加了银行卡返回的回调 会显示最后一个,即最新一个
- (void)getBankCardList:(BOOL)selectLastCard {
    
    [MBManager showLoading];
    [FPBankCardModel getCardListSuccess:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        [MBManager hideLoading];
        
        [self.bankCardSource removeAllObjects];
        
        for (FPBankCardModel *model in list) {
            
            [self.bankCardSource addObject:model];
            
            model.isSelect = NO;
        }
        
        FPBankCardModel *model = list.firstObject;
        self.bankCardSelectIndex = 0;
        
        if (selectLastCard) {
            
            model = list.lastObject;
            self.bankCardSelectIndex = list.count - 1;
            model.isSelect = YES;
        }
        else {
            
            model = list.firstObject;
            model.isSelect = YES;
        }
        
        NSUInteger count = self.bankCardSource.count;
        CGFloat height = 0.f;
        
        if (self.bankCardSource.count > 3) {
            
            count = 3;
            height = 56.f * count + 30.f;
        }
        else if (self.bankCardSource.count == 0) {
            
            count = 1;
            height = 56.f * count + 30.f;
        }
        else {
            
            height = 56.f * count + 30.f;
        }
        
        [self.selectOtherLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectBankCardAction)]];
        self.tableView.frame = CGRectMake(0.f, 41.f, SCREEN_WIDTH - 32.f, 56.f * count);
        self.backViewHeight.constant = 256.f - 56.f * 3 + height - 30.f;
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 选择银行卡
- (void)selectBankCardAction {
    
    if (self.bankCardSource.count == 0) {
        
        [self addNewCardAction];
        return;
    }
    
    CGFloat popupHeight = 70.f + 58.f; // 其他控件的高度
    
    if (self.bankCardSource.count < 6) {
        
        popupHeight += 68.f * self.bankCardSource.count;
    }
    else {
        
        popupHeight += 68.f * 6;
    }
    
    FPCustomPopupView *popupView = [[FPCustomPopupView alloc] initWithHeight:popupHeight];
    self.bankCardInfoMainView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPBankCardInfoMainView.class) owner:nil options:nil].lastObject;
    [popupView.contentView addSubview:self.bankCardInfoMainView];
    popupView.tag = 9000;
    
    self.bankCardInfoMainView.dataSource = self.bankCardSource;
    
    self.bankCardInfoMainView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, popupHeight);
    
    // 显示弹窗
    [popupView showInView:self.view];
    
    WeakSelf;
    self.bankCardInfoMainView.selectBankCardBlock = ^(NSInteger index) {
        
//        FPBankCardModel *model = weakSelf.bankCardSource[index];
//        weakSelf.cardLab.text = [NSString stringWithFormat:@"%@(%@)", model.affiliation , [model.cardNumber substringFromIndex:(model.cardNumber.length - 4)]];
//        weakSelf.cardLogoImgView.image = IMG(model.logo.length > 0 ? model.logo : @"icon_bank_card_default");
        weakSelf.bankCardSelectIndex = index;
//        [weakSelf showText:[NSString stringWithFormat:@"选中银行卡第~%zd",index]];
        [popupView dismiss];
    };
    
    [self.bankCardInfoMainView.bottomView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addNewCardAction)]];
}

#pragma mark - 添加银行卡
- (void)addNewCardAction {
    
    FPCustomPopupView *view = (FPCustomPopupView *)[self.view viewWithTag:9000];
    [view dismiss];
    
    FPAddNewBankCardController *vc = [[FPAddNewBankCardController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
    // 刷新银行卡列表
    WeakSelf;
    vc.bankCardBlock = ^() {
        
        [weakSelf getBankCardList:YES];
//        weakSelf.headerView.bankCardLab.text = [NSString stringWithFormat:@"%@(%@)", model.affiliation , [model.cardNumber substringFromIndex:(model.cardNumber.length - 4)]];
//        self.headerView.bankCardImgView.image = IMG(model.logo.length > 0 ? model.logo : @"icon_bank_card_default");
    };
}


- (void)initVerView {
    
    self.codeWindow.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.6f];
    [self.view addSubview:self.codeWindow];
    
    self.whiteView.backgroundColor = [UIColor whiteColor];
    self.whiteView.clipsToBounds = YES;
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.01, 1.01, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.99, 0.99, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [self.whiteView.layer addAnimation:animation forKey:nil];
    self.whiteView.layer.cornerRadius = 10.f;
    [self.codeWindow addSubview:self.whiteView];
    
    CGFloat w_width = self.whiteView.width;
    
    self.tip = [[UILabel alloc] initWithFrame:CGRectMake(30, 24.f, w_width - 60, 60)];
    [self.whiteView addSubview:self.tip];
    
    NSString *phone = [FPUserInfoModel.sharedUserInfo.phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    
    self.tip.text = [NSString stringWithFormat:@"我们已向您的银行卡预留手机号%@发送了一条短信验证码，请注意查收", phone];
    self.tip.textAlignment = NSTextAlignmentLeft;
    self.tip.font = [UIFont systemFontOfSize:14.f weight:(UIFontWeightMedium)];
    self.tip.textColor = [UIColor hexColor:@"#3A3A3A"];
    self.tip.backgroundColor = [UIColor clearColor];
    self.tip.numberOfLines = 0;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 260.f - 68.f, w_width / 2.f, 68.f)];
    [self.whiteView addSubview:leftView];
    leftView.backgroundColor = UIColor.clearColor;
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(w_width / 2.f, 260.f - 68.f, w_width / 2.f, 68.f)];
    [self.whiteView addSubview:rightView];
    rightView.backgroundColor = UIColor.clearColor;
    
    CGFloat btnWidth = leftView.width - 48.f;
    
    UIButton *close = [UIButton buttonWithType:UIButtonTypeCustom];
    close.frame = CGRectMake(leftView.width / 2.f - btnWidth / 2.f, 0, btnWidth, 44);
    close.backgroundColor = [UIColor clearColor];
    [close setTitle:@"取消" forState:UIControlStateNormal];
    [close setTitleColor:MAIN_BLUE_COLOR forState:UIControlStateNormal];
    [close addTarget:self action:@selector(hideWindow) forControlEvents:UIControlEventTouchUpInside];
    [leftView addSubview:close];
    close.clipsToBounds = YES;
    close.layer.borderWidth = 1.f;
    close.layer.cornerRadius = 22.f;
    close.layer.borderColor = MAIN_BLUE_COLOR.CGColor;
    
    UIButton *confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    confirm.frame = CGRectMake(rightView.width / 2.f - btnWidth / 2.f, 0, btnWidth, 44);
    confirm.backgroundColor = [UIColor clearColor];
    [confirm setTitle:@"确定" forState:UIControlStateNormal];
    [confirm setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(hideWindow) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:confirm];
    confirm.clipsToBounds = YES;
    confirm.layer.cornerRadius = 22.f;
    confirm.backgroundColor = MAIN_BLUE_COLOR;
    
    [self.verView removeFromSuperview];
    self.verView = [[MQVerCodeInputView alloc]initWithFrame:CGRectMake(30, self.tip.bottom + 20.f, self.whiteView.width - 60, 50)];
    self.verView.maxLenght = 4;//最大长度
    self.verView.keyBoardType = UIKeyboardTypeNumberPad;
    [self.verView mq_verCodeViewWithMaxLenght];
    [self.whiteView addSubview:self.verView];
    self.verView.viewColor = [UIColor hexColor:@"#ECF3FF"]; //UIColor.clearColor;
    self.verView.viewColorHL = [UIColor hexColor:@"#ECF3FF"]; //UIColor.clearColor;
    
    __weak typeof(self) weakSelf = self;
    self.verView.block = ^(NSString *text){
        
        if (text.length == 4) {
            
            weakSelf.code = text;
            [weakSelf hideWindow];
            
//            [MBManager showLoading];
//            [weakSelf performSelector:@selector(callbackResult) withObject:nil afterDelay:1.5f];
        }
    };
}

#pragma mark - 提示验证码错误
- (void)callbackResult {
    
//    [MBManager hideLoading];
//    [self showText:@"验证码错误"];
    
    FPRepayResultController *vc = [[FPRepayResultController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loadWebVerificode {
    
    
    // 加载人机验证
//    [[NDAPIClient sharedInstance] requestWithURLString:[MAIN_URL stringByAppendingString:LOGIN_VERTIFY_CODE_TOKEN_URL] parameters:nil type:HttpRequestTypePost success:^(id responseObject, NSString *msg, BOOL successRet) {
//
//        NSError *error;
//
//        id object = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
//
//        BOOL ret = [[object objectForKey:@"success"] boolValue];
//
//        if (ret == NO) {
//
//            [self showText:[object objectForKey:@"message"]];
//
//            [self performSelector:@selector(hideWindow) withObject:nil afterDelay:1.f];
//        }
//        else {
//
//            self.key = [object objectForKey:@"data"];
//
//            NSMutableDictionary *param = [NSMutableDictionary dictionary];
//            [param setObject:self.key forKey:@"key"];
//
//            //获取图片
//            [[NDAPIClient sharedInstance] requestWithURLString:[MAIN_URL stringByAppendingString:LOGIN_VERTIFY_CODE_URL] parameters:param type:HttpRequestTypeGet success:^(id responseObject, NSString *msg, BOOL successRet) {
//
//                [self hideSpinView];
//
//                self.codeImageView.image = [UIImage imageWithData:responseObject];
//
//            } failure:^(NSError *error) {
//
//                [self showError:error];
//
//                [self performSelector:@selector(hideWindow) withObject:nil afterDelay:1.f];
//            }];
//        }
//
//    } failure:^(NSError *error) {
//
//        [self showError:error];
//        NSLog(@"%@",error.userInfo);
//
//        [self performSelector:@selector(hideWindow) withObject:nil afterDelay:1.5f];
//    }];
}

- (void)hideWindow {
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 1.5;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    animation.values = values;
    [self.whiteView.layer addAnimation:animation forKey:nil];
    
    [UIView animateWithDuration:1.5 animations:^{
        
//        self.codeWindow.alpha = 0;
        
    } completion:^(BOOL finished) {
        
        [self.codeWindow.subviews.copy enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromSuperview];
        }];
        
        self.codeWindow.hidden = YES;
        self.codeWindow = nil;
    }];
}

#pragma mark - lazy loads
- (UIView *)codeWindow {
    
    if (!_codeWindow) {
        
        _codeWindow = [[UIView alloc] initWithFrame:self.view.bounds];
    }
    return _codeWindow;
}

- (UIView *)whiteView {
    
    if (!_whiteView) {
    
        _whiteView = [[UIView alloc] initWithFrame:CGRectMake(30, SCREEN_HEIGHT / 2 - 220, SCREEN_WIDTH - 60, 260)];
    }
    return _whiteView;
}

@end
